import React, { Component } from "react";
import PubSub from 'pubsub-js';
import axios from 'axios';
export default class HeroList extends Component {

    state = {
        heros: [],
        //是否初始化状态
        isInit: true
    }

    render() {
        //解构赋值
        let {isInit, heros} = this.state;

        return (
            <div className="hero-list">
                {
                    this.state.isInit && <div className="welcome">欢迎来到英雄联盟</div>
                }
                
                {
                    this.state.heros.map(item => {
                        return <div className="item" key={item.id}>
                                    <img
                                        width="100%"
                                        src={item.avatar}
                                        alt=""
                                    />
                                    <p>{item.name}</p>
                                </div>
                    })
                }

                {
                    // 如果请求之后 heros 依然为空 则显示暂无数据
                    !isInit && heros.length === 0  && <div className="empty">
                                                暂无数据
                                            </div>
                }
                
                
            </div>
        );
    }

    //组件挂载完毕
    componentDidMount(){
        //订阅频道
        PubSub.subscribe('keywords',async (_, data) => {
            //发送请求获取英雄的数据
            let result = await axios('http://api.xiaohigh.com:8090/lol?q='+data);
            //保存数据
            this.setState({
                heros: result.data,
                isInit: false, //取消初始化状态
            })
        })
    }

    //取消订阅  完善工作
    componentWillUnmount(){
        PubSub.unsubscribe('keywords');
    }
}
